package com.journey.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.journey.api.IUserService;
import com.journey.common.Const;
import com.journey.common.ResponseCode;
import com.journey.common.ServerResponse;
import com.journey.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by ADMIN on 2018/3/16.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    //注入服务提供方暴露的接口，通过@Reference注解，dubbo会在扫描的时候自动代理接口，然后通过rpc调用远程服务。
    //如果用xml配置方式，需要将@Reference换成@Autowired。
    @Autowired
//    @Reference
    IUserService userService;

    // 用户登录
    @RequestMapping("/login")
    @ResponseBody //将NoteResult转成json输出
    public ServerResponse<String> login(String name, String pwd, HttpSession session) {
        //调用业务组件处理
        ServerResponse<String> response = userService.checkLogin(name, pwd);
        if (response.isSuccess()) {
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        return response;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public ServerResponse<String> logout(HttpSession session) {
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getCode(), "退出成功");
    }

    @RequestMapping("/register")
    @ResponseBody
    public ServerResponse<User> regist(String name, String pwd, String nickname) {
        ServerResponse<User> response = userService.regist(name, pwd, nickname);
        return response;
    }

    @RequestMapping("/get_user_info")
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }

        return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
    }
}
